package com.change.core.jackson;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;

import java.io.IOException;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * LocalDateSerializer
 *
 * @author linqunxun
 * @date 2021/9/10 10:24 上午
 */
public class LocalDateSerializer extends StdSerializer<LocalDate> {

    public LocalDateSerializer(){
        super(LocalDate.class);
    }

    @Override
    public void serialize(LocalDate value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        if (value != null) {
            if(provider.isEnabled(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)) {
                final long mills = value.atStartOfDay(ZoneOffset.systemDefault()).toInstant().toEpochMilli();
                gen.writeNumber(mills);
            }else {
                gen.writeString(value.format(DateTimeFormatter.ISO_LOCAL_DATE));
            }
        } else {
            gen.writeNull();
        }
    }
}
